package com.tecnap.app.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import com.tecnap.R;
import com.tecnap.app.LampEntity;
import com.tecnap.app.database.LampDataSource;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class DataActivity extends Activity {

	private String clickedLampNumber;
	private LampDataSource lampDataSource;
	
	private SimpleAdapter adapter;
	private List<HashMap<String, String>> fillMaps;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.data);
		
		// Database table "lamp" Connector
		lampDataSource = new LampDataSource(this);
	}
	
	@Override
	public void onResume() {
		super.onResume();
		
		// Open connection to Database
		lampDataSource.open();
		
		// Prepare the list of all records
		fillMaps = new ArrayList<HashMap<String, String>>();
		
		List<LampEntity> allLamps = lampDataSource.getAllLamps();
		
		Iterator<LampEntity> it = allLamps.iterator();
		
		while (it.hasNext()){
			HashMap<String, String> map = new HashMap<String, String>();
			LampEntity le = it.next();
			map.put("col_1", le.getNumber().toString());
			Float fPositionX = le.getPositionX();
			String positionX = fPositionX.toString();
			if (positionX.length()>7) positionX = positionX.substring(0, 7);
			Float fPositionY = le.getPositionY();
			String positionY = fPositionY.toString();
			if (positionY.length()>7) positionY = positionY.substring(0, 7);
			map.put("col_2", positionX + " " + positionY);
			map.put("col_3", le.getType().toString());
			map.put("col_4", le.getPower().toString());
			map.put("col_5", le.getBrand().toString());
			map.put("col_6", le.getModel().toString());
			map.put("col_7", le.getComment().toString());
			fillMaps.add(map);
		}

		// create the grid item mapping
		String[] from = new String[] { "col_1", "col_2", "col_3", "col_4",
				"col_5", "col_6", "col_7" };
		int[] to = new int[] { R.id.dge_item1, R.id.dge_item2, R.id.dge_item3,
				R.id.dge_item4, R.id.dge_item5, R.id.dge_item6, R.id.dge_item7 };
		// fill in the grid_item layout
		adapter = new SimpleAdapter(this, fillMaps,
				R.layout.datagridelement, from, to);

		// Deve essere definita FINAL altrimenti non possiamo recuperare
		// l'elemento
		// durante l'OnItemClick: Guardare sotto
		final ListView lv = (ListView) findViewById(R.id.listview);

		lv.setAdapter(adapter);
		lv.setTextFilterEnabled(true);

		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// Recupero l'elemento selezionato
				// In questo caso è un HashMap (guarda oggetto map per la
				// popolazione della listview)
				@SuppressWarnings("unchecked")
				HashMap<String, String> selectedItem = (HashMap<String, String>) lv.getItemAtPosition(position);
				
				// When clicked, show a Dialog
				setClickedLampNum(selectedItem.get("col_1"));
				
				showLampDialog( lv.getItemAtPosition(position) );
			}
		});
	}
	
	@Override
	public void onPause(){
		super.onPause();
		
		// Open connection to Database
		lampDataSource.close();
	}
	
	private void showLampDialog(final Object o) {
		AlertDialog dialog = new AlertDialog.Builder(this).create();
		dialog.setMessage("Azioni sulla Lampada N°: " + getClickedLampNumber());
		dialog.setButton(DialogInterface.BUTTON_POSITIVE,
				"Modifica dato", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						
						// Retrieve the MainActivity
						MainActivity parent = (MainActivity) getParent();
						// Set data to exchange with the FormActivity
						parent.putExtra("lampNumber", getClickedLampNumber());
						// Switch to the FormActivity
			            parent.switchTab(MainActivity.tabs.FORM);
					}
				});
		dialog.setButton(DialogInterface.BUTTON_NEUTRAL,
				"Elimina dato", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						confirmDeleteDialog(o);
					}
				});
		dialog.setButton(DialogInterface.BUTTON_NEGATIVE,
				"Annulla", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		dialog.show();

	}
	
	private void confirmDeleteDialog(final Object o){
		AlertDialog dialog = new AlertDialog.Builder(this).create();
		dialog.setMessage("Cancellare Lampada N°: " + getClickedLampNumber() + " ?");
		dialog.setButton(DialogInterface.BUTTON_POSITIVE,
				"Si", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						if (lampDataSource.removeLampByNumber(getClickedLampNumber())) {
							fillMaps.remove((HashMap<String, String>) o);
							adapter.notifyDataSetChanged();
						}
						dialog.dismiss();
					}
				});
		dialog.setButton(DialogInterface.BUTTON_NEGATIVE,
				"No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		dialog.show();
	}

	public String getClickedLampNumber() {
		return clickedLampNumber;
	}

	public void setClickedLampNum(String clickedLampNumber) {
		this.clickedLampNumber = clickedLampNumber;
	}

}
